package com.cn.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import com.cn.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/back/user/findAll")
public class UserFindAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//      0.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        1.取得页面数据
        String pageString = req.getParameter("page");
        String limitString = req.getParameter("limit");
        String username = req.getParameter("username");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex");
        String startBirthday = req.getParameter("start");
        String endBirthday = req.getParameter("end");
        String hobby = req.getParameter("hobby");
        String enable = req.getParameter("enable");

//        这里的目的，就是防止分页传递过来的参数不合法，比如空，字符串等
//        if (pageString == null||"a".equals(pageString)) {
//            pageString = "1";
//        }
//        if (limitString == null) {
//            limitString = "10";
//        }
        int page = Tool.getPage(pageString);
        int limit = Tool.getLimit(limitString);
//       2. 封装对象
        UserModel userModel = new UserModel();
        userModel.setPage(page);
        userModel.setLimit(limit);
        userModel.setUsername(Tool.nullToStr(username));
        userModel.setEnable(Tool.stringToInt(enable));
        userModel.setPhone(Tool.nullToStr(phone));
        userModel.setSex(Tool.nullToStr(sex));
        userModel.setStartBirthday(Tool.nullToStr(startBirthday));
        userModel.setEndBirthday(Tool.nullToStr(endBirthday));
//        userModel.setBirthday(birthday);
        userModel.setHobby(Tool.nullToStr(hobby));
        userModel.setAddress(Tool.nullToStr(address));
//        3.调用服务逻辑层
        UserService userService = new UserServiceImpl();
        //        4.得到逻辑层返回数据
        ResultModel resultModel = userService.findAll(userModel);
        //        5.将数据返回给前端
        resp.getWriter().println(JSONObject.toJSONString(resultModel));
    }
}
